package samoloty.controler;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.TextArea;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import samoloty.model.IDataModel;
import samoloty.model.models.HoldsModel;
import samoloty.model.models.PaxModel;
import samoloty.model.models.StabTrimModel;
import samoloty.view.DisplayPanel;
import samoloty.view.MainWindow;
import samoloty.view.MyButton;

/**
 *
 * @author borysfan
 */
public class DisplayPanelControler implements MyControler {

    private DisplayPanel panel;
    private Controler controler;
    private IDataModel dataModel;
    private String textContent;
    private int edno = 0;

    public DisplayPanelControler(Controler c) {
        controler = c;
        initPanel();
    }

    public DisplayPanelControler(Controler c, IDataModel data) {
        controler = c;
        dataModel = data;
        initPanel();
    }

    public void initPanel() {
        panel = new DisplayPanel();
        initData();
    }

    public DisplayPanel getPanel() {
        return panel;
    }

    public void setUpWindow() {
        MainWindow window = controler.getView();
        window.setLeftPanelVisible(true);
        window.setRightPanelVisible(true);
        window.setAllBtnStyle(MyButton.ACTIVE_BUTTON);
        window.setDisplayBtnStyle(MyButton.CHOOSE_BUTTON);
        //controler.getPlotPanelControler().update();
        panel.firstFocused();
    }

    public void reset() {
        edno = 0;
        panel.reset();
    }

    public void setDataModel(IDataModel dataModel) {
        this.dataModel = dataModel;
        edno++;
        initData();
    }

    private void initData() {
    }

    public String update() {
        controler.getInfoPanelControler().update();
        edno++;
        edno %= 100;
        textContent = new String();
        textContent = "  L O A D S H E E T           CHECKED          APPROVED      EDNO\n"
                + "  ALL WEIGHTS IN KILOGRAM     %prepared%                 %edno%\n"
                + "  \n"
                + "  FROM/TO FLIGHT      A/C REG VERSION       CREW     DATE    TIME\n"
                + "  %vorigin% %vdestination% %vflightnum%    %vacreg%  %vconfig%       %vcrew%   %date% %time%\n"
                + "                          WEIGHT            DISTRIBUTION         \n"
                + "  LOAD IN COMPARTMENTS    %vttlholdssw% %holdsline1%\n"
                + "                                        %holdsline2%\n"
                + "  PASSENGER/CABIN BAG     %vttlpaxw% %vpaxline% TTL %vttlpax1%\n"
                + "                                 PAX C/Y %vpaxcy%\n"
                + "  TOTAL TRAFFIC LOAD      %vttl%\n"
                + "  DRY OPERATING WEIGHT    %vdow%\n"
                + "  ZERO FUEL WEIGHT ACTUAL %vazfw% MAX %vmzfw%      ADJ\n"
                + "  TAKE OFF FUEL           %vtof%\n"
                + "  TAKE OFF WEIGHT ACTUAL  %vatow% MAX %vmtow%      ADJ\n"
                + "  TRIP FUEL               %vtf% \n"
                + "  LANDING WEIGHT ACTUAL   %valaw% MAX %vmlaw%      ADJ\n"
                + "  \n"
                + "  BALANCE AND SEATING CONDITIONS        LAST MINUTE CHANGES\n"
                + "  DOI   %vdoi%                    DEST  SPEC   CL/CPT  + - WEIGHT\n"
                + "  LIZFW %vzfwi%  MACZFW %vmaczfw%  .                             .\n"
                + "  LITOW %vtowi%  MACTOW %vmactow%  .                             .\n"
                + "  LILAW %vlawi%  MACLAW %vmaclaw%  .                             .\n"
                + "                                  .                             .\n"
                + "  STAB TO %vstab%          .                             .\n"
                + "                                  .                             .\n"
                + "  SEATING                         .                             .\n"
                + "  %seatingline1%           .                             .\n"
                + "                                  ...............................\n"
                + "  UNDERLOAD BEFORE LMC    %vul%             LMC TOTAL + -       \n"
                + "  \n"
                + "  CAPTAINS INFORMATION/NOTES\n"
                + "  BW %vbasicweight%  BI %vbasicindex%\n"
                + "  \n"
                + "  SI\n"
                + "  %vsi1%\n"
                + "  %vsi2%\n"
                + "  %vsi3%\n"
                + "  %vsi4%\n"
                + "  %vsi5%\n"
                + "  %vsi6%\n"
                + "  %vsi7%\n";

        //prepared 15 znakow
        String prepared = controler.getFlightControler().getVPreparedBy();
        textContent = textContent.replaceFirst("%prepared%", fill2MinimalLength(prepared, 15, true));

        String vorigin = controler.getFlightControler().getVOrigin();//3 znaki
        textContent = textContent.replaceFirst("%vorigin%", fill2MinimalLength(vorigin, 3, true));

        String vdestination = controler.getFlightControler().getVDestination();//3 znaki
        textContent = textContent.replaceFirst("%vdestination%", fill2MinimalLength(vdestination, 3, true));

        String vflightnumber = controler.getFlightControler().getVFlightNumber();//8 znakow
        textContent = textContent.replaceFirst("%vflightnum%", fill2MinimalLength(vflightnumber, 8, true));

        String vvacreg = controler.get_vacreg();//6 znakow
        textContent = textContent.replaceFirst("%vacreg%", fill2MinimalLength(vvacreg, 6, true));

        textContent = textContent.replaceFirst("%edno%", fill2MinimalLength(Integer.toString(edno), 2, false));

        String vconfig = controler.getDowPanelControler().get_vconfig().getConfiguration();
        textContent = textContent.replaceFirst("%vconfig%", fill2MinimalLength(vconfig, 7, true));

        String vcrew = controler.getDowPanelControler().get_vcrew().getDisplay();
        textContent = textContent.replaceFirst("%vcrew%", fill2MinimalLength(vcrew, 6, true));
        String date = "";
        String day = controler.getFlightControler().getVDay();
        String month = controler.getFlightControler().getVMonth();
        String year = controler.getFlightControler().getVYear();
        year = year.substring(2);
        date = day + month + year;
        textContent = textContent.replaceFirst("%date%", fill2MinimalLength(date, 7, true));

        String time = controler.getFlightControler().getVTime();
        textContent = textContent.replaceFirst("%time%", fill2MinimalLength(time, 4, true));

        String vttl = Long.toString(Math.round(controler.getInfoPanelControler().compute_vttl()));
        textContent = textContent.replaceFirst("%vttl%", fill2MinimalLength(vttl, 6, false));

        String vdow = Long.toString(Math.round(controler.getInfoPanelControler().compute_vdow()));
        textContent = textContent.replaceFirst("%vdow%", fill2MinimalLength(vdow, 6, false));

        String vazfw = Long.toString(Math.round(controler.getInfoPanelControler().compute_azfw()));
        textContent = textContent.replaceFirst("%vazfw%", fill2MinimalLength(vazfw, 6, false));

        int computation = controler.getInfoPanelControler().getComputation();
        String vmzfw = Integer.toString(controler.getInfoPanelControler().get_vmzfw());
        if (computation == 1) {
            vmzfw += "   L";
        } else {
            vmzfw += "    ";
        }
        textContent = textContent.replaceFirst("%vmzfw%", fill2MinimalLength(vmzfw, 10, false));

        String vtof = controler.getFuelPanelControler().get_vtof();
        textContent = textContent.replaceFirst("%vtof%", fill2MinimalLength(vtof, 6, false));

        String vatow = Long.toString(Math.round(controler.getInfoPanelControler().compute_vatow()));
        textContent = textContent.replaceFirst("%vatow%", fill2MinimalLength(vatow, 6, false));

        dataModel = controler.getDataModel();
        int c_vmtow = Integer.parseInt(controler.getDowPanelControler().get_vmtow());
        int d_vmtow = dataModel.getMaxWeights().getTakeOff();//max tow z info
        int c_vmlaw = Integer.parseInt(controler.getDowPanelControler().get_vmlaw());
        int d_vmlaw = dataModel.getMaxWeights().getLanding();// max law z info
        int vmtow = d_vmtow;
        int vmlaw = d_vmlaw;
        if (c_vmtow < d_vmtow) {
            vmtow = c_vmtow;
        }
        if (c_vmlaw < d_vmlaw) {
            vmlaw = c_vmlaw;
        }


        String s_vmtow = Integer.toString(vmtow);
        if (computation == 2) {
            s_vmtow += "   L";
        } else {
            s_vmtow += "    ";
        }
        textContent = textContent.replaceFirst("%vmtow%", fill2MinimalLength(s_vmtow, 10, false));

        String vtf = controler.getFuelPanelControler().get_vtf();
        textContent = textContent.replaceFirst("%vtf%", fill2MinimalLength(vtf, 6, false));

        String valaw = Long.toString(Math.round(controler.getInfoPanelControler().compute_valaw()));
        textContent = textContent.replaceFirst("%valaw%", fill2MinimalLength(valaw, 6, false));

        String s_vmlaw = Integer.toString(vmlaw);
        if (computation == 3) {
            s_vmlaw += "   L";
        } else {
            s_vmlaw += "    ";
        }
        textContent = textContent.replaceFirst("%vmlaw%", fill2MinimalLength(s_vmlaw, 10, false));

        String vdoi = getStringWithPrecision(controler.getInfoPanelControler().compute_vdoi(), 2);
        textContent = textContent.replaceFirst("%vdoi%", fill2MinimalLength(vdoi, 6, false));

        String vzfwi = getStringWithPrecision(controler.getInfoPanelControler().compute_vzfwi(), 2);
        textContent = textContent.replaceFirst("%vzfwi%", fill2MinimalLength(vzfwi, 6, false));

        String vmaczfw = getStringWithPrecision(controler.getInfoPanelControler().compute_vmaczfw(), 2);
        textContent = textContent.replaceFirst("%vmaczfw%", fill2MinimalLength(vmaczfw, 9, false));

        String vtowi = getStringWithPrecision(controler.getInfoPanelControler().compute_vtowi(), 2);
        textContent = textContent.replaceFirst("%vtowi%", fill2MinimalLength(vtowi, 6, false));

        String vmactow = getStringWithPrecision(controler.getInfoPanelControler().compute_vmactow(), 2);
        textContent = textContent.replaceFirst("%vmactow%", fill2MinimalLength(vmactow, 9, false));

        String vlawi = getStringWithPrecision(controler.getInfoPanelControler().compute_vlawi(), 2);
        textContent = textContent.replaceFirst("%vlawi%", fill2MinimalLength(vlawi, 6, false));

        String vmaclaw = getStringWithPrecision(controler.getInfoPanelControler().compute_vmaclaw(), 2);
        textContent = textContent.replaceFirst("%vmaclaw%", fill2MinimalLength(vmaclaw, 9, false));

        String vbasicweight = controler.getDowPanelControler().get_vbasicweight();
        textContent = textContent.replaceFirst("%vbasicweight%", fill2MinimalLength(vbasicweight, 6, true));

        String vbasicindex = controler.getDowPanelControler().get_vbasicindex();
        textContent = textContent.replaceFirst("%vbasicindex%", fill2MinimalLength(vbasicindex, 2, true));

        //SEATING SECTION
        String seatingLine1 = new String();
        dataModel = controler.getDataModel();
        ArrayList<PaxModel> paxModel = dataModel.getPax();
        if (paxModel.size() > 0) {
            seatingLine1 += paxModel.get(0).getSection() + "/" + fill2MinimalLength(controler.getPaxPanelControler().get_vpax0a(), 3, true) + " ";
        }
        if (paxModel.size() > 1) {
            seatingLine1 += paxModel.get(1).getSection() + "/" + fill2MinimalLength(controler.getPaxPanelControler().get_vpax0b(), 3, true) + " ";
        }
        if (paxModel.size() > 2) {
            seatingLine1 += paxModel.get(2).getSection() + "/" + fill2MinimalLength(controler.getPaxPanelControler().get_vpax0c(), 3, true) + " ";
        }
        textContent = textContent.replaceFirst("%seatingline1%", seatingLine1);
        //-----------------------------

        //SIPanel
        SiPanelControler siControler = controler.getSiPanelControler();
        siControler.update();
        String vsi1 = siControler.getVsi1();
        textContent = textContent.replaceFirst("%vsi1%", vsi1);
        String vsi2 = siControler.getVsi2();
        textContent = textContent.replaceFirst("%vsi2%", vsi2);
        String vsi3 = siControler.getVsi3();
        textContent = textContent.replaceFirst("%vsi3%", vsi3);
        String vsi4 = siControler.getVsi4();
        textContent = textContent.replaceFirst("%vsi4%", vsi4);
        String vsi5 = siControler.getVsi5();
        textContent = textContent.replaceFirst("%vsi5%", vsi5);
        String vsi6 = siControler.getVsi6();
        textContent = textContent.replaceFirst("%vsi6%", vsi6);
        String vsi7 = siControler.getVsi7();
        textContent = textContent.replaceFirst("%vsi7%", vsi7);
        //-------------------------


        //VSTAB
        String vstab = new String();

        StabTrimModel stabTrimFlap1 = dataModel.getStabTrimFlap1();
        String display1 = stabTrimFlap1.getStabTrimSubModel().get(0).getDisplay();
        double stabTrim1 = controler.getInfoPanelControler().setStabTrim1Lab();

        double stabTrim2 = controler.getInfoPanelControler().setStabTrim2Lab();
        StabTrimModel stabTrimFlap2 = dataModel.getStabTrimFlap2();
        String display2 = new String();
        if (stabTrimFlap2 != null) {
            display2 = stabTrimFlap2.getStabTrimSubModel().get(0).getDisplay();
        }

        if (InfoPanelControler.isZero(stabTrim2) == false) {
            vstab += fill2MinimalLength(getStringWithPrecision(stabTrim2, 1), 4, false);
            if (display2.equals("")) {
                vstab += "         ";
            } else {
                vstab += " FOR " + display2;
            }
        } else {
            vstab += fill2MinimalLength(getStringWithPrecision(stabTrim1, 1), 5, false);
            if (display1.equals("")) {
                vstab += "         ";
            } else {
                vstab += " FOR " + display1;
            }
        }

        textContent = textContent.replaceFirst("%vstab%", fill2MinimalLength(vstab, 14, false));

        //-------------------------------

        String vul = Integer.toString(controler.getInfoPanelControler().compute_vul());
        textContent = textContent.replaceFirst("%vul%", fill2MinimalLength(vul, 6, true));

        String holdsline1 = "";
        ArrayList<HoldsModel> holds = controler.getDataModel().getHolds();
        for (int i = 0; i < 4 && i < holds.size(); i++) {
            String holdName = holds.get(i).getHold();
            String tmp = "";
            if (holdName.equals("1")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold1());
            } else if (holdName.equals("2")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold2());
            } else if (holdName.equals("3")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold3());
            } else if (holdName.equals("4")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold4());
            } else if (holdName.equals("5")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold5());
            } else if (holdName.equals("5r")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold5r());
            } else if (holdName.equals("5l")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold5l());
            } else if (holdName.equals("6")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold6());
            }

            holdsline1 += holds.get(i).getHold() + "/" + fill2MinimalLength(tmp, 4, true);
            holdsline1 += " ";

        }
        holdsline1 = holdsline1.substring(0, holdsline1.length());

        String holdsline2 = "";
        for (int i = 4; i < holds.size(); i++) {
            String holdName = holds.get(i).getHold();
            String tmp = "";
            if (holdName.equals("1")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold1());
            } else if (holdName.equals("2")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold2());
            } else if (holdName.equals("3")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold3());
            } else if (holdName.equals("4")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold4());
            } else if (holdName.equals("5")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold5());
            } else if (holdName.equals("5r")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold5r());
            } else if (holdName.equals("5l")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold5l());
            } else if (holdName.equals("6")) {
                tmp = Integer.toString(controler.getHoldsPanelControler().get_vttlhold6());
            }

            holdsline2 += holds.get(i).getHold() + "/" + fill2MinimalLength(tmp, 4, true);
            holdsline2 += " ";
        }
        holdsline2 = holdsline2.substring(0, holdsline2.length());

        textContent = textContent.replaceFirst("%holdsline1%", holdsline1);
        textContent = textContent.replaceFirst("%holdsline2%", holdsline2);

        String vttlpaxw = Long.toString(Math.round(controler.getInfoPanelControler().compute_vttlpaxw()));
        textContent = textContent.replaceFirst("%vttlpaxw%", fill2MinimalLength(vttlpaxw, 6, false));

        String vttlholdssw = Integer.toString((int) controler.getInfoPanelControler().compute_vttlholdsw());
        textContent = textContent.replaceFirst("%vttlholdssw%", fill2MinimalLength(vttlholdssw, 6, false));

        String vpaxm = controler.getPaxPanelControler().get_vpaxm();
        String vpaxf = controler.getPaxPanelControler().get_vpaxf();
        String vpaxch = controler.getPaxPanelControler().get_vpaxch();
        String vpaxi = controler.getPaxPanelControler().get_vpaxi();
        textContent = textContent.replaceFirst("%vpaxline%", fill2MinimalLength(vpaxm + "/" + vpaxf + "/" + vpaxch + "/" + vpaxi, 15, true));

        String vttlpax1 = controler.getPaxPanelControler().get_vttlpax1();
        textContent = textContent.replaceFirst("%vttlpax1%", fill2MinimalLength(vttlpax1, 3, true));

        String vpaxc = controler.getPaxPanelControler().get_vpaxc();
        String vpaxy = controler.getPaxPanelControler().get_vpaxy();
        textContent = textContent.replaceFirst("%vpaxcy%", fill2MinimalLength(vpaxc + "/" + vpaxy, 7, true));
        panel.setText(textContent);
        return textContent;
    }

    /*uzupelnia spacjami napis tak aby jego dlugosc wynosila len. jezeli jest za dlugi zostaje skrocony
    zmienna end oznacza czy spacje sa dopisywane do konca. Jezeli jest rowna false spacje dopisuje do poczatku*/
    private String fill2MinimalLength(String s, int len, boolean end) {
        int strlen = s.length();
        if (strlen < len) {
            String gap = "";
            for (int i = 0; i < len - strlen; i++) {
                gap += " ";
            }
            if (end == false) {
                s = gap + s;
            } else {
                s = s + gap;
            }
        } else {
            s = s.substring(0, len);
        }
        return s;
    }

    public void printPage() {

        PageFormat format = new PageFormat();
        format.setOrientation(PageFormat.PORTRAIT);
        PrintDisplayPanel printPanel = new PrintDisplayPanel();
        printPanel.setText(this.update());


        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(printPanel, format);
        if (job.printDialog()) {
            try {
                job.print();
            } catch (PrinterException e) {
                System.err.println("DisplayPanelControler. Blad podczas drukowania");
            }
        }


    }

    String getStringWithPrecision(double value, int n) {
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(n);
        df.setMinimumFractionDigits(n);
        return df.format(value);
    }

    public void firstFocused() {
    }
}
